<?php
/*
 * Copyright (c) 2011 Todd Brady
 *
 * PS3Theatre is freely distributable under the terms of the MIT license.
 * For details, see the MIT-Licence web site: http://www.opensource.org/licenses/mit-license.php 
 */
 
 	require_once 'StringUtil.class.php';

    class TVDb
    {
       /*
        * thetvdb.com settings
        */
       private $api_key = '';
       private $lang = '';
       private $tvdbapiurl = '';
       
       
       /*
        * constructor
        * Initializes the class
        */
       public function __construct($apikey)
       {
          $this->api_key = $apikey;
          $this->lang = 'en';
          $this->tvdbapiurl = 'http://www.thetvdb.com/api/';
       }
       
       /*
        * This method returns the serie id for the given seriename
        */
		public function GetSeriesSearchArray($seriename, $year = "")
       	{
        //	$seriename = strtolower($seriename);
			$urlSeriesName = urlencode($seriename);
          	$url = $this->tvdbapiurl . 'GetSeries.php?seriesname=' . $urlSeriesName;
          	$feed = self::DownloadUrl($url);
          	$xml = simplexml_load_string($feed);
          	$node = $xml->Series->seriesid;
			
			//if year is set strip out shows with different year
			if($year != ""){
				$xml = self::cleanXmlArrayByYear($xml, $year);
			}
			
			//try and strip out shows that dont have the same title
			if($node !== NULL){
				if(self::resultCountAfterClean($xml, $seriename) == 1){
					return self::cleanXmlArray($xml, $seriename);
				}else{
					return $xml;
				}
   			}else{
				return false;
			}
       }
       
	   /*
        * This method returns the episode id for the
        * given serieid and season/episode number
        */
       public function GetEpisodeData($serieid,$s,$e)
       {
          $url = $this->tvdbapiurl . $this->api_key . '/series/' . $serieid . '/default/' . $s . '/' . $e . '/' . $this->lang. '.xml';
		  $feed = self::DownloadUrl($url);
		  
          if($feed){
             $xml = simplexml_load_string($feed);
             

             $episode['id'] = (int) $xml->Episode->id;
             $episode['serieid'] = (int) $xml->Episode->seriesid;
             $episode['season'] = (int) $xml->Episode->SeasonNumber;
             $episode['episode'] = (int) $xml->Episode->EpisodeNumber;
             $episode['airdate'] = (string) $xml->Episode->FirstAired;
             $episode['name'] = (string) $xml->Episode->EpisodeName;
             $episode['description'] = (string) $xml->Episode->Overview;
             
             return $episode;
          }else{
             return false;
          }
       }
       
       
       /*
        * This method returns information about the specified serie
        */
       public function GetSerieData($serieid,$getepisodes = false)
       {
          // get feed
          if($getepisodes === true){
             $url = $this->tvdbapiurl . $this->api_key. '/series/' . $serieid . '/all/' .$this->lang. '.xml';
          }else{
             $url = $this->tvdbapiurl . $this->api_key. '/series/' . $serieid . '/' .$this->lang. '.xml';
          }

          $feed = self::DownloadUrl($url);
          if($feed){
             $xml = simplexml_load_string($feed);
             
             $serie['id'] = (int) $serieid;
             $serie['name'] = (string) $xml->Series->SeriesName;
             $serie['description'] = (string) $xml->Series->Overview;
			 $serie['contentRating'] = (string) $xml->Series->ContentRating;
			 $serie['firstAired'] = (string) $xml->Series->FirstAired;
			 $serie['genre'] = (string) $xml->Series->Genre;
			 $serie['network'] = (string) $xml->Series->Network;
			 $serie['rating'] = (string) $xml->Series->Rating;
 			 $serie['runtime'] = (int) $xml->Series->Runtime;
             $serie['bannerUrl'] = (string) $xml->Series->banner;
             $serie['fanartUrl'] = (string) $xml->Series->fanart;
             $serie['posterUrl'] = (string) $xml->Series->poster;
             
             if($getepisodes === true){
                $episodes = Array();
                foreach($xml->Episode as $ep){
                   $episode['id'] = (int) $ep->id;
                   $episode['season'] = (int) $ep->SeasonNumber;
                   $episode['episode'] = (int) $ep->EpisodeNumber;
                   $episode['airdate'] = (string) $ep->FirstAired;
                   $episode['name'] = (string) $ep->EpisodeName;
                   $episode['description'] = (string) $ep->Overview;
                   $episodes['s'.$ep->SeasonNumber.'e'.$ep->EpisodeNumber] = $episode;
                }
                $serie['episodes'] = $episodes;
             }
             
             return $serie;
          }else{
             return false;
          }
       }
       
       /*
        * This method downloads a file by an url,
        * if the download fails it will retry, until the number of
        * retrys specified is reached. When the last try fails the
        * method will return false.
        */
       private static function DownloadUrl($url)
       {
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_HEADER, 1);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch,CURLOPT_ENCODING , "gzip");
		
			$response = curl_exec($ch);
			
			$httpCode = curl_getinfo($ch ,CURLINFO_HTTP_CODE);
			$headerSize = curl_getinfo($ch,CURLINFO_HEADER_SIZE);
            $data = substr( $response, $headerSize );
			curl_close($ch);

			if($httpCode != 200) {
			    return false;
			}
			
			return $data;
       }
	   
	   /*
	   	* This returns number of matches after the clean command
		* would be ran.	   
	   */
	   private function resultCountAfterClean($xml, $searchString){
	   		$returnXml = $xml;
			$needle = $searchString;
			$count = 0;
			//count($returnXml->Series);
			
	   		for($i=count($returnXml->Series)-1; $i>=0; $i--) {
				$haystack = StringUtil::createCleanTitle($returnXml->Series[$i]->SeriesName);
				
				if($haystack == $needle) {
					$count++;
				}
			}

			return $count;
	   }
	   
	   /*
	   	* This method takes the series search array and removes entries that are
		* not the same year as passed in and returns the cleaned
		* array.	   
	   */
	   private function cleanXmlArrayByYear($xml, $year){
	   		$returnXml = $xml;
			$needle = $year;
			
			for($i=count($returnXml->Series)-1; $i>=0; $i--) {
				$haystack = substr($returnXml->Series[$i]->FirstAired, 0, 4);

				if($haystack != $needle) {
					unset($returnXml->Series[$i]);
				}
			}
			
		   return $returnXml;
	   }
	   
	   /*
	   	* This method takes the series search array and removes entries that are
		* not exact matches of the search string and returns the cleaned
		* array.	   
	   */
	   private function cleanXmlArray($xml, $searchString){
	   		$returnXml = $xml;
			$needle = $searchString;
			
			for($i=count($returnXml->Series)-1; $i>=0; $i--) {
				$haystack = StringUtil::createCleanTitle($returnXml->Series[$i]->SeriesName);
			
				if($haystack != $needle) {
					unset($returnXml->Series[$i]);
			
				}
			}
			
			return $returnXml;
	   }
	}
?>
